<?php
/*
*	db函数库 @zairwolf
*/
if(!defined('IN')) exit('Access Denied');

function db_conn(){
	global $db,$db_host, $db_user, $db_code, $db_name;

	$db = mysql_connect($db_host, $db_user, $db_code);

	db_use($db_name);

	db_charset();
	db_mode();
}

function db_q($sql){
	global $querynum;
	$query = @mysql_query($sql);
	if($mysql_error=mysql_error()){
		db_halt('MYSQL error',$sql."<br />".$mysql_error);
	}
	$querynum++;
	return $query;
}

function db_i($sql){
	db_q($sql);

	return mysql_insert_id();
}

function db_r($sql, $rst = MYSQL_ASSOC){
	$rs=db_q($sql);
	if(false === $rs)
		return false;

	return mysql_fetch_array($rs, $rst);
}

function db_rows($sql, $rst = MYSQL_ASSOC){
	$rs=db_q($sql);
	$rows = array();
	while($row = mysql_fetch_array($rs, $rst))
		$rows[] = $row;

	return $rows;
}

function db_num($rs){
	return mysql_num_rows($rs);
}

function db_affect_rows(){
	return mysql_affected_rows();
}

function db_use($db_name){
	return mysql_select_db($db_name);
}

function db_charset($charset = 'utf8'){
	if(version_compare(db_ver(), '4.1', '<'))
		return -1;

	return db_q('SET character_set_connection='.$charset.', character_set_results='.$charset.', character_set_client=binary');
}

function db_mode($mode = ''){
	if(version_compare(db_ver(), '5.0.1', '<'))
		return -1;

	return db_q('SET sql_mode=\''.$mode.'\'');
}

function db_ver($server = true){
	if($server) {
		return mysql_get_server_info();
	}else {
		return mysql_get_client_info();
	}
}

function db_info($sql){
	return db_r(db_explain($sql));
}

function db_explain($what){
	return db_q('EXPLAIN '.$what);
}

function db_halt($msg = '', $sql = ''){
	exit( $msg.'<br />'.$sql.'<br />');
}
